package com.kgc.javaweb.dao.impl;

import com.kgc.javaweb.dao.OwnerDao;
import com.kgc.javaweb.entity.Owner;
import com.kgc.javaweb.enums.CodeMsg;
import com.kgc.javaweb.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class OwnerDaoImpl implements OwnerDao {
    @Override
    public Owner selectById(String id) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql="select * from owner where id =?";
        try {
            Owner owner = queryRunner.query(sql, new BeanHandler<Owner>(Owner.class),id);
            return owner;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public void update(Owner owner) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "update owner set sex = ? ,tel = ? ,address = ? where username = ?";


        try {
            queryRunner.update(sql,owner.getSex(),owner.getTel(),owner.getAddress(),owner.getUsername());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw  new RuntimeException(CodeMsg.UPDATE_FAIL.getMsg());
        }
    }

    @Override
    public void repair(String name, String address) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "insert into repairtype (name,address)values(?,?)";


        try {
            int update = queryRunner.update(sql, name, address);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw  new RuntimeException(CodeMsg.UPDATE_FAIL.getMsg());
        }
    }

    @Override
    public void updateUserInfoPwdById(String newPassword, Integer id) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "update owner set password = ?  where id = ?";
        try {
            queryRunner.update(sql, newPassword ,id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw  new RuntimeException(CodeMsg.UPDATE_FAIL.getMsg());
        }
    }
    @Override
    public Owner findOwnerByUserNameAndPassword(String username, String password) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "select *  from owner where username = ?  and password = ?";
        try {
            Owner owner = queryRunner.query(sql, new BeanHandler<Owner>(Owner.class), username, password);
            return owner;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw  new RuntimeException("查询失败");
        }
    }

}
